package com.zprmb.udzt;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.util.BitmapUtils;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.Regular;
import com.zprmb.udzt.util.TimeCount;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.vo.AuthFailureError;
import com.zprmb.udzt.vo.Request.Method;
import com.zprmb.udzt.vo.RequestQueue;
import com.zprmb.udzt.vo.Response;
import com.zprmb.udzt.vo.VolleyError;
import com.zprmb.udzt.vo.toolbox.HttpClientStack;
import com.zprmb.udzt.vo.toolbox.HttpStack;
import com.zprmb.udzt.vo.toolbox.ImageRequest;
import com.zprmb.udzt.vo.toolbox.JsonObjectRequest;
import com.zprmb.udzt.vo.toolbox.Volley;

/**
 * 忘记密码
 *
 * @author shenshao
 */
public class ForgetPwd extends BaseActivity implements OnClickListener {
    private EditText et_tel, et_code, et_pwd, et_imgCaptcha;
    private Button btn_send_mes, btn_confirm;
    private TimeCount timeCount;
    private ImageView img_captcha, img_back;
    private String csrf;
    private RequestQueue mQueue;
    private RelativeLayout rl_back;
    private ImageView pass;
    String mobile = "";
    private TextView tv_voice_code;
    private TextView tv_comment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forgetpwd);
        setTitle("找回登录密码", this);
        BbtApplication.getInstance().addActvity(this);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        CookieStore cookieStore = new BasicCookieStore();
        httpclient.setCookieStore(cookieStore);
        HttpStack httpStack = new HttpClientStack(httpclient);
        tv_comment = (TextView) findViewById(R.id.tv_comment);
        tv_voice_code = (TextView) findViewById(R.id.tv_voice_code);
        mQueue = Volley.newRequestQueue(this, httpStack);
        et_tel = (EditText) findViewById(R.id.et_tel);
        et_pwd = (EditText) findViewById(R.id.new_pwd);
        tv_voice_code = (TextView) findViewById(R.id.tv_voice_code);
        et_code = (EditText) findViewById(R.id.forget_captcha);
        img_back = (ImageView) findViewById(R.id.img_back);
        et_imgCaptcha = (EditText) findViewById(R.id.froget_img_captcha);
        img_captcha = (ImageView) findViewById(R.id.img_captcha);
        btn_send_mes = (Button) findViewById(R.id.btn_send_mes);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        pass = (ImageView) findViewById(R.id.img_pass);
        tv_voice_code.setText(Html.fromHtml("收不到短信？点击获取" + "<font color='#00aaee'>语音验证码</font>"));

        if (Regular.isMobileNO(et_tel.getText().toString())) {
            btn_send_mes.setVisibility(View.VISIBLE);
            tv_voice_code.setVisibility(View.VISIBLE);
        } else {
            btn_send_mes.setVisibility(View.GONE);
            tv_voice_code.setVisibility(View.GONE);
        }
        tv_voice_code.setOnClickListener(this);
        rl_back.setOnClickListener(this);
        img_back.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
        btn_send_mes.setOnClickListener(this);
        img_captcha.setOnClickListener(this);
        pass.setOnClickListener(this);
        setEditTextInhibitInputSpace(et_pwd);
        et_tel.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (Regular.isMobileNO(s.toString())) {
                    btn_send_mes.setVisibility(View.VISIBLE);
                    tv_voice_code.setVisibility(View.VISIBLE);
                } else {
                    btn_send_mes.setVisibility(View.GONE);
                    tv_voice_code.setVisibility(View.GONE);
                }
            }
        });
        et_pwd.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (et_pwd.getText().toString().equals("")) {
                    pass.setVisibility(View.GONE);
                } else {
                    pass.setVisibility(View.VISIBLE);
                }
            }
        });
        if (getIntent().getStringExtra("mobile") != null && getIntent().getStringExtra("mobile").equals("")) {

            mobile = "";
        } else {
            mobile = getIntent().getStringExtra("mobile");
        }
        et_tel.setText(mobile);
        if (Regular.isMobileNO(et_tel.getText().toString())) {
            btn_send_mes.setVisibility(View.VISIBLE);
            tv_voice_code.setVisibility(View.VISIBLE);
        } else {
            btn_send_mes.setVisibility(View.GONE);
            tv_voice_code.setVisibility(View.GONE);
        }
        timeCount = new TimeCount(60000, 1000, btn_send_mes, tv_voice_code);
        initcaptcha();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        BbtApplication.getInstance().removeActvity(this);
    }

    private void initcaptcha() {
        // TODO Auto-generated method stub
        ImageRequest imageRequest = new ImageRequest(
                Constant.URL + "/captcha.png",
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        img_captcha.setImageBitmap(response);
                    }
                }, 0, 0, Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                img_captcha.setImageResource(R.drawable.bbt_bg);
            }
        });
        mQueue.add(imageRequest);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btn_confirm:
                if (et_code.getText().toString().equals("")) {
                    Toast.makeText(ForgetPwd.this, "请先输入验证码", 2000).show();
                    return;
                }
                if (et_pwd.getText().toString().equals("")) {
                    Toast.makeText(ForgetPwd.this, "请输入新密码", 2000).show();
                    return;
                }
//			if(!Regular.getPass(et_pwd.getText().toString().trim())){
//				Toast.makeText(ForgetPwd.this, "“登录密码可以为6-16位字符，可使用字母且分区大小写、数字、下划线且不包含空格”", 2000).show();
//				return;
//			}
                update();
                break;
            case R.id.btn_send_mes:
                if (et_tel.getText().toString().equals("")) {
                    Toast.makeText(ForgetPwd.this, "请先输入手机号", 2000).show();
                    return;
                }
                if (et_imgCaptcha.getText().toString().equals("")) {
                    Toast.makeText(ForgetPwd.this, "请先输入图形验证码", 2000).show();
                    return;
                }
                initData(0);
                break;
            case R.id.img_captcha:

                initcaptcha();
                break;
            case R.id.img_back:

                finish();
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.img_pass:
                if (et_pwd.getTransformationMethod().equals(PasswordTransformationMethod
                        .getInstance())) {
                    et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pass.setBackgroundResource(R.drawable.yan1);
                } else {
                    et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pass.setBackgroundResource(R.drawable.yan2);
                }
                break;
            case R.id.tv_voice_code:
                if (et_tel.getText().toString().equals("")) {
                    Toast.makeText(ForgetPwd.this, "请先输入手机号", 2000).show();
                    return;
                }
                if (et_imgCaptcha.getText().toString().equals("")) {
                    Toast.makeText(ForgetPwd.this, "请先输入图形验证码", 2000).show();
                    return;
                }
                initData(1);
                break;
        }

    }

    private void changeCommentStatus(int status, String comment) {
        if (status == 1) {
            if (tv_comment.getVisibility() == View.GONE) {
                tv_comment.setVisibility(View.VISIBLE);
                tv_comment.setText(comment);
            }
        } else {
            if (tv_comment.getVisibility() == View.VISIBLE) {
                tv_comment.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (tv_comment != null) {

            if (tv_comment.getVisibility() == View.VISIBLE) {
                tv_comment.setVisibility(View.GONE);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void initData(final int approach) {
        // 这个接口返回的请求头里有3个参数，，前两个暂时写死！
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                try {

                    if (jsonObject.optInt("success") == 1) {
                        csrf = jsonObject.getJSONObject("data").optString(
                                "csrf");

                        initmessage(approach);
                    } else {

                        Toast.makeText(ForgetPwd.this,
                                jsonObject.optString("comment"), 0).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        vollery.setHeaders("appId", "bbt3.0:android");
        vollery.setHeaders("appSecret", "RH89xcYh");
        vollery.setHeaders("appVersion", getAppVersion());
        vollery.setRequestMethod(1);

        vollery.execute(this, Constant.URL + "api/csrf", "");
    }

    private void update() {
        AjaxParams params = new AjaxParams();
        params.put("mobile", et_tel.getText().toString());
        params.put("mobileCaptcha", et_code.getText().toString());
        params.put("newPassword", et_pwd.getText().toString());
        VolleryUtil volleryUtil = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                if (jsonObject.optInt("success") == 1) {
                    Toast.makeText(ForgetPwd.this, jsonObject.optString("comment"), 2000).show();
                    finish();
                } else {
                    changeCommentStatus(1, jsonObject.optString("comment"));
                }
                Log.e("reset", jsonObject.toString());
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };

        volleryUtil.setRequestMethod(1);
        volleryUtil.execute(ForgetPwd.this, Constant.URL + "/api/v5/login/resetPassword?", params.toString());


    }

    private void initmessage(final int approach) {
        String capt = et_imgCaptcha.getText().toString();
        AjaxParams params = new AjaxParams();

        params.put("imgCaptcha", capt);
        params.put("approach", approach + "");

        params.put("mobile", et_tel.getText().toString());
        JsonObjectRequest json = new JsonObjectRequest(Method.GET,
                Constant.URL + "/api/v5/login/sendMobCaptchaForResetPassword?" + params.toString(), null, new Response.Listener<JSONObject>() {
            public void onResponse(JSONObject response) {

//					Log.e("froget", response.toString());
                if (response.optInt("success") == 1) {

                    timeCount.start();
                    if (approach == 1) {

                        tv_voice_code.setText("您将会接到电话播报验证码，请保持手机畅通");
                    }
                } else {

                    initcaptcha();

                    if (!response.optString("comment").equals("")) {
                        changeCommentStatus(1, response.optString("comment"));
                    }
                }
            }
        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
//					Log.e("error", error.toString());
            }
        }) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("csrf", csrf);
                return headers;
            }
        };
        mQueue.add(json);


    }

}
